package cn.jiedh.app.meiweidk.homepage.category;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import cn.jiedh.app.meiweidk.MyWebActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.EmptyRecyclerView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.UI.VerticalSpaceItemDecoration;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.baseadapter.BaseAdapter;
import cn.jiedh.app.meiweidk.baseadapter.BaseViewHolder;
import cn.jiedh.app.meiweidk.entity.BannerEntity;
import cn.jiedh.app.meiweidk.entity.LoanListBean;
import cn.jiedh.app.meiweidk.loan.LoanDetailActivity;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;


/**
 * @name：MXK
 * @author：达摩
 * @phone：
 * @createTime： 十月-23
 * @modifyTime： 21:16:10
 * @explain：首页点击的分类页面
 */
public class CategoryActivity extends BaseActivity {

    @BindView(R.id.bar_tv_title)
    TextView title;
    @BindView(R.id.category_img)
    ImageView imageView;
    @BindView(R.id.category_rv)
    EmptyRecyclerView myListView;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;
    @BindView(R.id.empty_nn_pic)
    ImageView emptyNnPic;
    @BindView(R.id.empty_nn_btn)
    TextView emptyNnBtn;
    @BindView(R.id.statelayout)
    StateLayout statelayout;

    int pageNo = 1;
    int indexSearchId;//模块ID
    int type = 0;////1APP原生 2 H5

    private List<LoanListBean.DataList> loanList = new ArrayList<>();
    BaseAdapter baseAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_category;
    }

    @Override
    protected void initView(View view) {
        statelayout.setOnNoClick(new StateLayout.NoNetView() {
            @Override
            public void setOnclck(View view) {
                smartrefreshLayout.autoRefresh();
            }
        });
        String titleStr = "";
        title.setText(getResources().getString(R.string.app_name));
        try {
            titleStr = getIntent().getExtras().getString("title");
            indexSearchId = getIntent().getExtras().getInt("indexSearchId");
            type = getIntent().getExtras().getInt("type");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(titleStr)) {
            title.setText(titleStr);
        }
        setBack(true);
        myListView.setLayoutManager(new LinearLayoutManager(this));
        myListView.addItemDecoration(new VerticalSpaceItemDecoration(15, false));
        smartrefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        smartrefreshLayout.setEnableLoadmoreWhenContentNotFull(true);
        smartrefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNo = 1;
                        getData();
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 2000);
            }
        });
        smartrefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNo++;
                        getData();
                        refreshlayout.finishLoadmore();
                    }
                }, 2000);
            }
        });
        smartrefreshLayout.autoRefresh();
    }

    private View emptyview;

    @Override
    protected void initData() {
        emptyview = findViewById(R.id.emptyview);
        emptyNnPic.setImageResource(R.mipmap.mydkcp);
        emptyNnBtn.setText("没有贷款产品哦～");
        baseAdapter = new BaseAdapter<LoanListBean.DataList>(this, R.layout.loan_list_item, loanList) {
            @Override
            public void convert(BaseViewHolder holder, LoanListBean.DataList bean, int position) {
                holder.setText(R.id.loan_title, bean.getName());
                holder.setText(R.id.loan_advert, bean.getAdver());
                String rate = "";
                if (1 == bean.getRateType()) {
                    rate = bean.getRate() + "%";
                } else if (2 == bean.getRateType()) {
                    rate = bean.getRate() + "%";
                }
                holder.setText(R.id.loan_daily_rate, rate);
                double successRate = Double.valueOf(bean.getSuccessRate().trim());
                String successRateStr = successRate + "%";
                holder.setText(R.id.loan_success_rate, successRateStr);
                holder.setText(R.id.rate_type_tv, "参考"+bean.getRateTypeStr()+"利率");
                String moneyMin = bean.getMoneyMin() + "";
                String moneyMax = bean.getMoneyMax() + "";
                if (moneyMin.length() >= 6) {
                    moneyMin = bean.getMoneyMin() / 10000 + "";
                } else {
                    moneyMin = bean.getMoneyMin() + "";
                }
                if (moneyMax.length() >= 6) {
                    moneyMax = bean.getMoneyMax() / 10000 + "万";
                } else {
                    moneyMax = bean.getMoneyMax() + "";
                }
                holder.setText(R.id.loan_quota, moneyMin + "-" + moneyMax);
                if (0 == bean.getHotWhether()) {
                    holder.getView(R.id.hot_img).setVisibility(View.GONE);
                } else if (1 == bean.getHotWhether()) {
                    holder.getView(R.id.hot_img).setVisibility(View.VISIBLE);
                }
                holder.setImageUrl(R.id.loan_icon, bean.getImgUrl());
                holder.setOnclickListener(R.id.item_layout, v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", bean.getName());
                    bundle.putInt("productId", bean.getProductId());
                    SPUtils.saveBuried("click","0","卡片位-列表-" + bean.getName(),"",
                            "卡片位-列表","","","");
                    ActivityUtil.next(CategoryActivity.this, LoanDetailActivity.class, bundle);
                });


                TextView goApply_tv=holder.getView(R.id.goApply_tv);
                goApply_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        apply(bean.getProductId(),bean.getApplyUrl(),bean.getName());
                    }
                });
            }
        };
        myListView.setAdapter(baseAdapter);
        getData();
    }


    /**
     * 统计并跳转
     *
     * @param productId
     * @param applyUrl
     * @param loanTitle
     */
    private void apply(int productId, String applyUrl, String loanTitle) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId + "");
        request(UrlUtils.ADDBROWSE, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                dismissLoadingDialog();
                if (0 == response.getCode()) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", applyUrl);
                    bundle.putString("title", loanTitle);
                    Intent intent = new Intent(CategoryActivity.this, MyWebActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                } else {
                    T.showShort(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.show(msg);
                dismissLoadingDialog();
            }
        });
    }

    /**
     * 获取数据
     */
    void getData() {
        Map map = new HashMap<String, Objects>();
        map.put("indexSearchId", indexSearchId);//最小金额(搜索条件,0为不传)
        map.put("pageNo", pageNo); //	是	int	首页模块ID
        map.put("pageSize", 10);//	否	int	第几页(如果模块类型是H5，可以不传)

        request(this, UrlUtils.HOME_PRODUCT_SEARCH, map, false, new ResponseSuccess<LoanListBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoanListBean> response) {
                if (response.getCode() != 0) {
                    T.showShortToast(response.getMessage());
                } else {
                    if (type == 1) {//1APP原生 2 H5
                        if (response.getData().getBannerImgUrl() != null) {
                            imageView.setVisibility(View.VISIBLE);
                            LoadUtils.loadImage(CategoryActivity.this,response.getData().getBannerImgUrl(),imageView);

//                            Glide.with(CategoryActivity.this).load(response.getData().getBannerImgUrl()).placeholder(R.drawable.green_loading).error(R.drawable.load_fail).into(imageView);
                        } else {
                            imageView.setVisibility(View.GONE);
                        }
                        if (pageNo == 1) {
                            loanList.clear();
                        }
                        loanList.addAll(response.getData().getDataList());
                        myListView.setEmptyView(emptyview);
                        baseAdapter.notifyDataSetChanged();
                    } else {//1APP原生 2 H5
                        BannerEntity bannerEntity = new BannerEntity();
                        bannerEntity.setShareLink(response.getData().getShareLink());
                        bannerEntity.setShareImgUrl(response.getData().getShareImgUrl());
                        bannerEntity.setShareTitle(response.getData().getShareTitle());
                        bannerEntity.setShareContent(response.getData().getShareContent());
                        bannerEntity.setLink(response.getData().getLink());

                        Bundle bundle = new Bundle();
                        bundle.putString("url", bannerEntity.getLink());
                        bundle.putString("title", title.getText().toString());
                        bundle.putInt("id", indexSearchId);
                        bundle.putInt("source", 1);
                        bundle.putSerializable("Hot", bannerEntity);
                        ActivityUtil.next(CategoryActivity.this, MyWebActivity.class, bundle);
                        finish();
                    }
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("获取模块数据错误" + msg);
                T.showShortToast(msg);
            }
        });
    }
}
